<template>
<div class="shLayout" @click="isShowInput = true" :style="[showInputBoxStyle,theme]">
    <div>
        <input  class="inputBox" 
                :style="isShowInput?{'background':theme['--backgroundColor']}:{ 'background':theme['--hoverLableColor']}" 
                v-model="inputVal"
                :placeholder="inputDef"
                @keydown.enter="goSearch()"
                 />
    </div>
    <div>
        <el-icon size="20"><Search /></el-icon>
    </div>
</div> 
<div class="cardBox" v-show="isShowInput && !isShowFuzzySearch">
    <div>
        <p>搜索历史</p>
        <p @click="clearSearchHistory">清空</p>
    </div>
    <div class="historyBox" :style="isShowMore?'height: 62px':''">
        <p v-for="item in searchHistory" :key="item">
            <span>{{ item }}</span>
            <span class="close" @click="delHistory(item)">
                <el-icon><CircleCloseFilled /></el-icon>
            </span>
        </p>
    </div>
    <div>
        <span v-if="isShowMore" @click="isShowMore = false">展开更多<el-icon><ArrowDown /></el-icon></span>
        <span v-else @click="isShowMore = true">收起<el-icon><ArrowUp /></el-icon></span>
    </div>
    <template v-if="hotSearchInfo">
        <div class="hotSearchBox">
            <div>{{ hotSearchInfo?.title }}</div>
            <div class="hotSearchItem">
                <router-link    :to="{ path:'/search',query:{'keyword':item.show_name} }" 
                                v-for="(item,index) in hotSearchInfo?.list" 
                                :key="item.keyword"
                                target="_blank"
                                >  
                    <span :style="index <= 2?{ 'color':theme['--titleColor'] }:''">{{ index + 1 }}</span>
                    <span>{{ item.show_name }}</span>
                    <img :src="item.icon" v-if="item.icon"/>
                </router-link>
            </div>
        </div>
    </template>
</div>
<div class="fuzzySearch" v-show="isShowInput && isShowFuzzySearch">
    <ul>
        <li v-for="(item,index) in fuzzySearchList" :key="index" @click="goSearch(item.value)" > <!--@keydown.down=""-->
            <span v-html="item.name"></span>
        </li>
    </ul>
</div>
    
</template>

<script lang="ts" setup>
import { ref,computed,watch,Ref,onMounted } from 'vue'
import { getThemes,resType } from '@/hooks/theme'
import { useRouter } from 'vue-router'
import { getWbiKeys,encWbi,encQuery } from '@/api/getVideo'
import { get } from '@/http/axios'
import { getCookies } from '@/utils/cookies'
import { useStore } from 'vuex'
import { getLocation, setLocation, clearByName, delLocation } from '@/utils/location'

interface info {
    goto:string
    icon:string     //内容后的插图
    keyword:string  
    show_name:string    //展示信息
    uri:string
}
interface resqType{
    list:Array<info>
    title:string
    top_list:Array<any>
    trackid:string
}

let isShowInput = ref<boolean>(false)
const router = useRouter()
const store = useStore()
let theme: Ref<resType> = ref(getThemes(router.currentRoute.value.name as string))
let hotSearchInfo = ref<resqType>()
let isShowMore = ref<boolean>(true)
let isShowFuzzySearch = ref<boolean>(false)
let inputVal = ref<string>()
let inputDef = ref<string>()
let fuzzySearchList = ref()
let searchHistory = ref<string[]>(getLocation('search'))

onMounted(() => {
    getDefaultShowTxt()
})

const showInputBoxStyle = computed(() => {
    if (isShowInput.value) {
        return 'border-bottom-left-radius: 0;border-bottom-right-radius:0;'
    } else return
})
function goSearch(val?:string){
    let key = null
    if (val) key = val
    else key = inputVal.value?inputVal.value:inputDef.value

    isShowInput.value = false
    isShowFuzzySearch.value = false

    if (key && !searchHistory.value.find(el => el === val)) {
        setLocation('search', key)
        searchHistory.value = getLocation('search')
    }

    let routeData = router.resolve({path:'/search', query:{'keyword':key  }})
    window.open(routeData.href, '_blank')
}
function isMyNode(e) {
    isShowInput.value = recursion(e.target)
}
//递归查找节点
function recursion(e): boolean{
    if (e.parentNode.id === 'mySearch') {
        return true
    } else if (e.parentNode.id === 'home') {
        return false
    } else {
        return recursion(e.parentNode)
    }
}
//卡片中的清除所有搜索记录
function clearSearchHistory(){
    clearByName('search')
    searchHistory.value = []
}
//删除某个收缩记录
function delHistory(item:string){
    delLocation('search', item)
    searchHistory.value = getLocation('search')
}
function getHotSearch(){    
    const wbi_keys = getWbiKeys(store)
    const query = encWbi(
    {
        limit:10,
        platform:'web'
    },
    wbi_keys.img_key, 
    wbi_keys.sub_key
    )
    get('/x/web-interface/wbi/search/square?' + query)
    .then(res => {
        hotSearchInfo.value = res.data.trending
    }).catch(res => {
        alert('热搜加载失败了')
    })
}
//默认状态下input展示内容
function getDefaultShowTxt() {
    const wbi_keys = getWbiKeys(store)
    const query = encWbi(
        {},
        wbi_keys.img_key, 
        wbi_keys.sub_key
    )
    get('/x/web-interface/wbi/search/default?' + query)
    .then(res => {
        inputDef.value = res.data.show_name
    }).catch(res => {
        alert('搜索框默认加载失败')
    })
}
//input输入字符时 模糊查询数据展示在卡片中
function getFuzzySearch(val:string){
    const query = encQuery(
        {
            func: 'suggest',
            suggest_type: 'accurate',
            sub_type: 'tag',
            main_ver: 'v1',
            highlight:'',
            userid: getCookies('DedeUserID'),
            bangumi_acc_num: 1,
            special_acc_num: 1,
            topic_acc_num: 1,
            upuser_acc_num: 3,
            tag_num: 10,
            special_num: 10,
            bangumi_num: 10,
            upuser_num: 3,
            term:  val,
            rnd: Math.random(),
            buvid:getCookies('buvid3'),
            spmid: 333.1007,
        }
    )
    get('/main/suggest?' + query,'','/csearch').then(res => {
        console.log('参数列表',res);
        fuzzySearchList.value = res.result.tag
    }).catch(err => {
        console.log('参数BUVid过期啦 请更换');
        
    })
}
//监听是否展开弹出内容 并决定是否启动全局监听器
watch(() =>isShowInput.value, (val) => {
    getHotSearch()
    if (val) window.addEventListener('click',isMyNode,true)
    else  window.removeEventListener('click',isMyNode,true)
})
watch(() => inputVal.value,(val) => {
    if (val){
        isShowFuzzySearch.value = true
        getFuzzySearch(val)
    } else {
        isShowFuzzySearch.value = false
    }

})
</script>

<style lang="scss" scoped>
$sysPopoverBackground: var(--backgroundColor);
$sysPopoverTitleColor: var(--titleColor);
$sysPopoverLableColor: var(--lableColor);
$sysPopoverHoverLableColor: var(--hoverLableColor);
$sysSearchBack:var(--searchItemBack);
@media  screen and (min-width: 0) and (max-width: 1200px){
    .hotSearchItem{
        & a{
            width: 100%;
        }
    }
}
@media  screen and (min-width: 1200px) and (max-width: 1600px){
    .hotSearchItem{
        & a{
            width: 48%;
        }
    }
}
@media  screen and (min-width: 1600px) and (max-width: 2400px){
    .hotSearchItem{
        & a{
            width: 45%;
        }
    }
}
ul{
    list-style: none;
    padding: 0;
    margin: 0;
}
li{
    padding: 0;
    margin: 0;
}
p{
    margin: 0;
    padding: 0;
}
.shLayout{
    position: relative;
    width: 100%;
    height: 100%;
    background: $sysPopoverHoverLableColor;
    border-radius: 8px;
    opacity: 0.95;
    padding: 0 5px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap:20px;
    &:hover{
        opacity: 1;
    }
    & div:nth-child(1){
        width: 90%;
        height: 100%;
        @include flexRowCenter;
        transition: all .3s;
        color: $sysPopoverLableColor;
    }
    & div:nth-child(2){
        padding: 0 10px;
        height: 80%;
        border-radius: 4px;
        color: $sysPopoverTitleColor;
        @include flexRowCenter;
        transition: all .3s;
    }
    & div:nth-child(2):hover{
        background:$sysPopoverHoverLableColor;
    }
}
.cardBox{
    z-index: 999;
    position: absolute;
    top: 100%;
    width: 100%;
    background: $sysPopoverBackground;
    border: 1px solid $sysPopoverHoverLableColor;
    border-top: none;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
    display: flex;
    flex-direction: column;
    padding-bottom: 10px;
    box-sizing: border-box;
    & div:nth-child(1){
        padding: 0 15px;
        box-sizing: border-box;
        width: 100%;
        height: 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: $sysPopoverTitleColor;
    }
    & div:nth-child(1) p{
        font-size: 17px;
        line-height: 20px;
        width: 50%;
        height: 100%;
        @include noWrap;
        text-align: left;
        display: flex;
        align-items: center;
    }
    & div:nth-child(1) p:nth-child(2){
        justify-content: end;
        font-size: 13px;
        color: $sysPopoverLableColor;
        cursor: pointer;
    }
    & div:nth-child(3){
        margin-top: 5px;
        width: 100%;
        @include flexRowCenter;
        color: $sysPopoverLableColor;
    }
    & div:nth-child(3) span{
        cursor: pointer;
        @include flexRowCenter;
    }
    & div:nth-child(3):hover{
        color: #409EFF;
    }
}
.historyBox{
    padding: 5px 15px;
    display: flex;
    gap: 10px;
    overflow: hidden;
    flex-wrap: wrap;
    & p{
        height: 25px;
        max-width: 100px;
        @include flexRowCenter;
        border-radius: 4px;
        padding: 5px 10px;
        box-sizing: border-box;
        background: $sysSearchBack;
        color: $sysPopoverTitleColor;
        cursor: pointer;
        position: relative;
    }
    & p span:nth-child(1){
        line-height: 15px;
        font-size: 12px;
        max-width: 90px;
        height: 15px;
        @include noWrap;
    }
    & p span:nth-child(2){
        color: $sysPopoverLableColor;
        position: absolute;
        top: -5px;
        right: -5px;
        opacity: 0;
    }
    & p:hover{
        color: #409EFF;
        .close{
            opacity: 1;
        }
    }
}
.hotSearchBox{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: $sysPopoverTitleColor;
    & div:nth-child(1){
        padding: 0 15px;
        box-sizing: border-box;
        font-size: 17px;
        line-height: 20px;
        width: 100%;
        @include noWrap;
        text-align: left;
        display: flex;
        align-items: center;
    }
}
.hotSearchItem{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 5px 0;
    width: 100%;
    & a{
        padding: 0 10px;
        box-sizing: border-box;
        height: 30px;
        display: flex;
        justify-content: start;
        align-items: center;
        border-radius: 4px;
        color: $sysPopoverTitleColor;
        transition: all .5s;
    }
    & a:hover{
        background: $sysPopoverHoverLableColor;
    }
    & a span:nth-child(1){
        margin-right: 5px;
        color: $sysPopoverLableColor;
    }
    & a span:nth-child(2){
        margin-right: 5px;
        color: $sysPopoverTitleColor;
        @include noWrap;
    }
    & a img{
        height: 15px;
        margin-left: 10px;
    }
}
.inputBox{
    width: 100%;
    height: 70%;
    outline: none;
    border: none;
    border-radius: 4px;
    background: $sysPopoverHoverLableColor;
}
.fuzzySearch{
    z-index: 999;
    position: absolute;
    top: 100%;
    width: 100%;
    background: $sysPopoverBackground;
    border: 1px solid $sysPopoverHoverLableColor;
    border-top: none;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
    display: flex;
    flex-direction: column;
    padding: 10px 0;
    box-sizing: border-box;
    & ul{
        display: flex;
        flex-direction: column;
        align-items: start;
        justify-content: center;
        color: $sysPopoverTitleColor;
    }
    & ul li{
        display: flex;
        justify-content: start;
        align-items: center;
        box-sizing: border-box;
        width: 100%;
        padding: 8px 15px;
        font-size: 14px;
        text-align: left;
        cursor: pointer;
    }
    & ul li:hover{
        background: $sysPopoverHoverLableColor;
    }
}
</style>